﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HHPS.CreditEducation.DataProvider;
using HHPS.CreditEducation.Frameworks.Commons;
using HHPS.CreditEducation.Frameworks.Constants;

namespace HHPS.CreditEducation.Presentation.Materials
{
    public partial class UniversityControl : UserControl
    {
        private readonly Business.Business _business;

        public UniversityControl()
        {
            InitializeComponent();
            _business = MainView.Instance.CreditEducationBusiness;
        }

        private void UniversityControlLoad(object sender, EventArgs e)
        {
            LoadFaculty();
            LoadCourse();

            Dock = DockStyle.Top;
        }

        #region -- Fauclty --

        /// <summary>
        /// This fuction loads facutly to datagridview
        /// </summary>
        private void LoadFaculty()
        {
            dgvFacultyList.DataSource = _business.GetListFacutly();

            DataGridViewHelper.ShowHideColumns(dgvFacultyList, new[]
                                                                   {
                                                                       (string) typeof (Faculty).Properties().IsChecked,
                                                                       (string) typeof (Faculty).Properties().Name
                                                                   });
            DataGridViewHelper.ShowIsCheck(dgvFacultyList);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvFacultyList, false);

            FacultyCurrentRowChanged();
        }

        private void ReloadFaculty(string facultyName)
        {
            LoadFaculty();
            DataGridViewHelper.SetDgvCurrentCell(dgvFacultyList, facultyName);
            FacultyCurrentRowChanged();

            if (dgvFacultyList.RowCount <= 0) txtFaculty.Text = string.Empty;
            else txtFaculty.SelectAll();
        }

        /// <summary>
        /// 
        /// </summary>
        private void FacultyCurrentRowChanged()
        {
            if (dgvFacultyList.CurrentRow != null)
            {
                txtFaculty.Text = dgvFacultyList.CurrentRow.Cells[(string)typeof(Faculty).Properties().Name].Value.ToString();
                LoadMajor();
            }

            else
            {
                lblMajor.Text = string.Format(ConstantMessages.LabelMajor, ConstantMessages.NoSelected);
                txtFaculty.Text = string.Empty;
                ckbAllFaculty.Checked = false;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgvFacultyListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvFacultyList == null ||
                dgvFacultyList.Columns[(string)typeof(Faculty).Properties().IsChecked] == null ||
                dgvFacultyList.Columns[(string)typeof(Faculty).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvFacultyList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvFacultyList[e.ColumnIndex, e.RowIndex].Value;

            ckbAllFaculty.Checked = DataGridViewHelper.AllRowsIsCheck(dgvFacultyList);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DgvFacultyListCurrentCellChanged(object sender, EventArgs e)
        {
            FacultyCurrentRowChanged();
        }

        /// <summary>
        /// Event CheckedChanged checkbox All faculty
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CkbAllFacultyCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvFacultyList, ckbAllFaculty.Checked);
        }

        /// <summary>
        /// Event click button Add faculty
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddFacutlyClick(object sender, EventArgs e)
        {
            try
            {
                var faculty = new Faculty { Name = txtFaculty.Text.Trim() };
                string message;

                if (_business.AddNewFacultyValidator(faculty, out message))
                {
                    _business.AddNewFaculty(faculty);

                    ReloadFaculty(faculty.Name);
                }
                else
                    MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click button edit faculty
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditFacultyClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvFacultyList.CurrentRow != null)
                {
                    var faculty = new Faculty
                                      {
                                          Id = Convert.ToInt32(dgvFacultyList.CurrentRow.Cells[(string)typeof(Faculty).Properties().Id].Value),
                                          Name = txtFaculty.Text.Trim()
                                      };
                    string message;

                    if (_business.EditFacultyValidator(faculty, out message))
                    {
                        if (!_business.EditFaculty(faculty))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.PROGRAM_NAME);
                            return;
                        }
                        ReloadFaculty(faculty.Name);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click button delete faculty
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteFacutlyClick(object sender, EventArgs e)
        {
            try
            {
                var faculties = new List<Faculty>();
                string message;

                for (var i = 0; i < dgvFacultyList.RowCount; i++)
                {
                    if (!(bool)dgvFacultyList[(string)typeof(Faculty).Properties().IsChecked, i].Value) continue;

                    faculties.Add(new Faculty
                                     {
                                         Id = (int)dgvFacultyList[(string)typeof(Faculty).Properties().Id, i].Value,
                                         Name = dgvFacultyList[(string)typeof(Faculty).Properties().Name, i].Value.ToString()
                                     });
                }

                if (faculties.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                    return;
                }

                if (_business.DeleteFacultiesValidator(faculties, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các khoa đã chọn"), FileConstants.PROGRAM_NAME, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteFaculties(faculties);
                        ReloadFaculty(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        #region -- Major --

        /// <summary>
        /// 
        /// </summary>
        private void LoadMajor()
        {
            if (dgvFacultyList.CurrentRow == null) return;

            var facultyId = Convert.ToInt32(dgvFacultyList.CurrentRow.Cells[PropertiesConstants.Id].Value);
            var nameFaculty = (dgvFacultyList.CurrentRow.Cells[PropertiesConstants.Name].Value);

            dgvMajorList.DataSource = _business.GetListMajorByIdFaculty(facultyId);

            lblMajor.Text = string.Format(ConstantMessages.LabelMajor,
                                          dgvCourseList.DataSource != null ? nameFaculty : ConstantMessages.NoSelected);

            DataGridViewHelper.ShowHideColumns(dgvMajorList,
                                               new[] { PropertiesConstants.IsChecked, PropertiesConstants.Name });
            DataGridViewHelper.ShowIsCheck(dgvMajorList);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvMajorList, false);

            MajorCurrentRowChanged();
        }

        private void ReloadMajor(Major major)
        {
            LoadMajor();
            DataGridViewHelper.SetDgvCurrentCell(dgvMajorList, major.Name);
            MajorCurrentRowChanged();
            if (dgvMajorList != null && dgvMajorList.RowCount > 0)
            {
                txtMajor.SelectAll();
            }
            else txtMajor.Text = string.Empty;
        }

        private void MajorCurrentRowChanged()
        {
            if (dgvMajorList.CurrentRow != null)
            {
                txtMajor.Text = dgvMajorList.CurrentRow.Cells[PropertiesConstants.Name].Value.ToString();
                LoadCapacity();
            }
            else
            {
                txtMajor.Text = string.Empty;

                ckbAllMajor.Checked = false;
                ckbAllMajor.Text = string.Format("Lựa chọn tất cả");

                lblCapacity.Text = string.Format(ConstantMessages.LabelCapacity, ConstantMessages.NoSelected);

                cboCourse.DataSource = null;
                cboCourse.DisplayMember = string.Empty;
                cboCourse.ValueMember = null;
            }
        }

        private void DgvMajorListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvMajorList == null || 
                dgvMajorList.Columns[PropertiesConstants.IsChecked] == null || 
                e.ColumnIndex != dgvMajorList.Columns[PropertiesConstants.IsChecked].Index)
                return;

            dgvMajorList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvMajorList[e.ColumnIndex, e.RowIndex].Value;

            ckbAllMajor.Checked = DataGridViewHelper.AllRowsIsCheck(dgvMajorList);
            ckbAllMajor.Text = string.Format((ckbAllMajor.Checked ? "Hủy" : "Lựa") + " chọn tất cả");
        }

        private void DgvMajorListCurrentCellChanged(object sender, EventArgs e)
        {
            MajorCurrentRowChanged();
        }

        private void CkbAllMajorClick(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvMajorList, ckbAllMajor.Checked);
            ckbAllMajor.Text = string.Format((ckbAllMajor.Checked ? "Hủy" : "Lựa") + " chọn tất cả");
        }

        /// <summary>
        /// Event click button Add Major
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddMajorClick(object sender, EventArgs e)
        {
            try
            {
                var major = new Major
                                  {
                                      Name = txtMajor.Text.Trim(),
                                      IdFaculty = dgvFacultyList.CurrentRow != null ?
                                      Convert.ToInt32(dgvFacultyList.CurrentRow.Cells[PropertiesConstants.Id].Value) : 0
                                  };

                string message;

                if (_business.AddNewMajorValidator(major, out message))
                {
                    _business.AddNewMajor(major);

                    ReloadMajor(major);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }     

        /// <summary>
        /// Event click edit Major
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditMajorClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvMajorList.CurrentRow != null)
                {
                    var major = new Major
                    {
                        Name = txtMajor.Text.Trim(),
                        IdFaculty = dgvFacultyList.CurrentRow != null ?
                        Convert.ToInt32(dgvFacultyList.CurrentRow.Cells[PropertiesConstants.Id].Value) : 0,
                        Id = Convert.ToInt32(dgvMajorList.CurrentRow.Cells[PropertiesConstants.Id].Value)
                    };
                    string message;

                    if (_business.EditMajorValidator(major, out message))
                    {
                        if (!_business.EditMajor(major))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.PROGRAM_NAME);
                            return;
                        }
                        ReloadMajor(major);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                }
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click Delete Major
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteMajorClick(object sender, EventArgs e)
        {
            try
            {
                var majors = new List<Major>();
                string message;

                for (var i = 0; i < dgvMajorList.RowCount; i++)
                {
                    if (!(bool)dgvMajorList[(string)typeof(Major).Properties().IsChecked, i].Value) continue;

                    majors.Add(new Major
                    {
                        Id = (int)dgvMajorList[(string)typeof(Major).Properties().Id, i].Value,
                        Name = dgvMajorList[(string)typeof(Major).Properties().Name, i].Value.ToString(),
                        IdFaculty = dgvFacultyList.CurrentRow != null ?
                         Convert.ToInt32(dgvFacultyList.CurrentRow.Cells[PropertiesConstants.Id].Value) : 0,
                    });
                }

                if (majors.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                    return;
                }

                if (_business.DeleteMajorsValidator(majors, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các ngành đã chọn"), FileConstants.PROGRAM_NAME, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteMajors(majors);
                        ReloadMajor(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        #region -- Course --

        private void LoadCourse()
        {
            dgvCourseList.DataSource = _business.GetListCourse();

            DataGridViewHelper.ShowHideColumns(dgvCourseList,
                                               new[] { PropertiesConstants.IsChecked, PropertiesConstants.Name });
            DataGridViewHelper.ShowIsCheck(dgvCourseList);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvCourseList, false);

            CourseCurrentRowChanged();
        }

        private void CourseCurrentRowChanged()
        {
            if (dgvCourseList.CurrentRow != null)
            {
                txtCourse.Text = dgvCourseList.CurrentRow.Cells[PropertiesConstants.Name].Value.ToString();
                LoadCapacity();
            }
            else
            {
                txtCourse.Text = string.Empty;

                ckbAllCourse.Checked = false;
                ckbAllCourse.Text = string.Format("Lựa chọn tất cả");

                lblCapacity.Text = string.Format(ConstantMessages.LabelCapacity, ConstantMessages.NoSelected);

                cboCourse.DataSource = null;
                cboCourse.DisplayMember = string.Empty;
                cboCourse.ValueMember = null;
            }
        }

        private void DgvCourseListCurrentCellChanged(object sender, EventArgs e)
        {
            CourseCurrentRowChanged();
        }

        private void CkbAllCourseCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvCourseList, ckbAllCourse.Checked);
            ckbAllCourse.Text = string.Format((ckbAllCourse.Checked ? "Hủy" : "Lựa") + " chọn tất cả");
        }

        private void DgvCourseListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvCourseList == null ||
                dgvCourseList.Columns[PropertiesConstants.IsChecked] == null ||
                e.ColumnIndex != dgvCourseList.Columns[PropertiesConstants.IsChecked].Index)
                return;

            dgvCourseList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvCourseList[e.ColumnIndex, e.RowIndex].Value;

            ckbAllCourse.Checked = DataGridViewHelper.AllRowsIsCheck(dgvCourseList);
            ckbAllCourse.Text = string.Format((ckbAllCourse.Checked ? "Hủy" : "Lựa") + " chọn tất cả");
        }

        /// <summary>
        /// Even click button Add Course 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddCourseClick(object sender, EventArgs e)
        {
            try
            {
                var course = new Course { Name = txtCourse.Text.Trim() };
                string message;

                if (_business.AddNewCourseValidator(course, out message))
                {
                    _business.AddNewCourse(course);

                    ReloadCourse(course);
                }
                else
                    MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void ReloadCourse(Course course)
        {
            LoadCourse();
            DataGridViewHelper.SetDgvCurrentCell(dgvCourseList, course.Name);
            CourseCurrentRowChanged();
            if (dgvCourseList != null && dgvCourseList.RowCount > 0)
            {
                txtCourse.SelectAll();
            }
            else txtCourse.Text = string.Empty;
        }

        /// <summary>
        /// Even click Edit Course
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditCourseClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvCourseList.CurrentRow != null)
                {
                    var course = new Course
                    {
                        Id = Convert.ToInt32(dgvCourseList.CurrentRow.Cells[(string)typeof(Course).Properties().Id].Value),
                        Name = txtCourse.Text.Trim()
                    };
                    string message;

                    if (_business.EditCourseValidator(course, out message))
                    {
                        if (!_business.EditCourse(course))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.PROGRAM_NAME);
                            return;
                        }
                        ReloadCourse(course);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        /// <summary>
        /// Event click button Delete Course
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnDeleteCourseClick(object sender, EventArgs e)
        {
            try
            {
                var courses = new List<Course>();
                string message;

                for (var i = 0; i < dgvCourseList.RowCount; i++)
                {
                    if (!(bool)dgvCourseList[(string)typeof(Course).Properties().IsChecked, i].Value) continue;
                    courses.Add(new Course
                    {
                        Id = (int)dgvCourseList[(string)typeof(Course).Properties().Id, i].Value,
                        Name = dgvCourseList[(string)typeof(Course).Properties().Name, i].Value.ToString(),
                    });
                }

                if (courses.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                    return;
                }

                if (_business.DeleteCoursesValidator(courses, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các kỳ đã chọn"), FileConstants.PROGRAM_NAME, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteCourses(courses);
                        ReloadCourse(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        #region -- Capacity --

        private void LoadCapacity()
        {
            if (dgvMajorList.CurrentRow == null || dgvCourseList.DataSource == null)
            {
                dgvCapacityList.Rows.Clear();
                return;
            }

            var majorId = Convert.ToInt32(dgvMajorList.CurrentRow.Cells[PropertiesConstants.Id].Value);


            dgvCapacityList.DataSource = _business.GetListCapacityByMajor(majorId);
            cboCourse.DataSource = _business.GetListCourse();
            cboCourse.DisplayMember = PropertiesConstants.Name;;
            cboCourse.ValueMember = PropertiesConstants.Id;
            lblCapacity.Text = string.Format(ConstantMessages.LabelCapacity,
                                            (dgvMajorList.CurrentRow.Cells[PropertiesConstants.Name].Value));

            DataGridViewHelper.ShowHideColumns(dgvCapacityList,
                                               new[] { PropertiesConstants.IsChecked, "MaxCredit", "MinCredit", "CourseName" });
            DataGridViewHelper.ShowIsCheck(dgvCapacityList);
            dgvCapacityList.Columns["CourseName"].DisplayIndex = 1;

            CapacityCurrentRowChanged();            
        }

        private void CapacityCurrentRowChanged()
        {
            if (dgvCapacityList.CurrentRow != null)
            {
                cboCourse.Text = dgvCapacityList.CurrentRow.Cells["CourseName"].Value.ToString();
                nudMax.Value = Convert.ToInt16(dgvCapacityList.CurrentRow.Cells["MaxCredit"].Value);
                nudMin.Value = Convert.ToInt16(dgvCapacityList.CurrentRow.Cells["MinCredit"].Value);
            }
            else
            {
                cboCourse.DataSource = null;
                cboCourse.DisplayMember = string.Empty;
                cboCourse.ValueMember = null;
            }
        }

        private void DgvCapacityListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvCapacityList == null ||
               dgvCapacityList.Columns[PropertiesConstants.IsChecked] == null ||
               e.ColumnIndex != dgvCapacityList.Columns[PropertiesConstants.IsChecked].Index)
                return;

            dgvCapacityList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvCapacityList[e.ColumnIndex, e.RowIndex].Value;
        }

        private void DgvCapacityListCurrentCellChanged(object sender, EventArgs e)
        {
            CapacityCurrentRowChanged();
        }
        /// <summary>
        /// Event click button Edit Capacity
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnEditCapacityClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvCapacityList.CurrentRow != null)
                {
                    var capacity = new Capacity
                    {
                        MinCredit = (int) nudMin.Value,
                        MaxCredit = (int) nudMax.Value,
                        IdCourse = Convert.ToInt32(dgvCapacityList.CurrentRow.Cells["IdCourse"].Value),
                        IdMajor = Convert.ToInt32(dgvCapacityList.CurrentRow.Cells["IdMajor"].Value),
                        Id = Convert.ToInt32(dgvCapacityList.CurrentRow.Cells[PropertiesConstants.Id].Value)
                    };
                    string message;

                    if (_business.EditCapacityValidator(capacity, out message))
                    {
                        if (!_business.EditCapacity(capacity))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.PROGRAM_NAME);
                            return;
                        }
                        LoadCapacity();
                        DataGridViewHelper.SetDgvCurrentCell(dgvCapacityList, capacity.CourseName);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.PROGRAM_NAME);
                }
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }        
        #endregion
    }
}